package lumis.service.wsrp.producer;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.event.IPortalEvent;
import lumis.portal.event.IPortalEventFilter;
import lumis.portal.event.IPortalEventObserver;
import lumis.portal.event.PortalEventFilters;
import lumis.portal.event.persistence.PreDeleteEvent;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceConfig;

import com.sun.portal.wsrp.producer.ProducerException;

/**
 * Observes the deletions of service interfaces in order to remove from any WSRPProducers's offered portlets.
*
 * @version $Revision: 11841 $ $Date: 2010-08-11 11:29:41 -0300 (Wed, 11 Aug 2010) $
 * @since 5.5.0
*/
public class ServiceInterfaceInstanceDeleteObserver implements IPortalEventObserver
{
	public IPortalEventFilter getEventFilter()
	{
		return PortalEventFilters.and(PortalEventFilters.byInstanceOf(PreDeleteEvent.class),
									  PortalEventFilters.byGroups(ServiceInterfaceInstanceConfig.class.getName()));
	}

	@SuppressWarnings("unchecked")
	public void onEvent(IPortalEvent event) throws PortalException
	{
		PreDeleteEvent pdEvent = (PreDeleteEvent)event;
	
		Collection<ServiceInterfaceInstanceConfig> entities = (Collection<ServiceInterfaceInstanceConfig>) pdEvent.getEntities();
		EntityManager entityManager = ManagerFactory.getEntityManager();
		
		// for each ServiceInterfaceInstanceConfig 
		for (ServiceInterfaceInstanceConfig serviceInterfaceInstance : entities)
		{
			// retrieves the list of WSRPProducers that use this interface instance
			Query query = entityManager.createNamedQuery(ProducerImpl.NAMED_QUERY_FIND_PRODUCERS_BY_OFFERED_PORTLETS);
			query.setParameter("interfaceInstanceId", serviceInterfaceInstance.getId());
			List<ProducerImpl> results = query.getResultList();
			
			// removes the serviceInterface from the offered portlets
			for (ProducerImpl producer : results)
			{
				try 
				{
					producer.removeOfferedPortlet(serviceInterfaceInstance.getId());
				} 
				catch (ProducerException e) 
				{
					throw new UnexpectedException(e);
				}
			}
		}
		entityManager.flush();
	}
}
 